﻿using System;
using System.Web.Mvc;
using System.Web;
using System.Web.Caching;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using Liber.WEB;
using Liber;

namespace SoBusiness.Controllers
{
    [NoSession]
    /// <summary>
    /// 此控制器是处理微信公众号tianlianb2b的交互入口
    /// </summary>
    public class TLB2BController : LiberController
    {
        protected static string myToken = "518518bug_20151212sobiz";  //此Token是申请公众号时设置，用于验证消息是否来自微信服务器
        protected static string aesKey= "A518518bug518518bug518518bug518518bug518518"; //用于微信通信过程中消息加密
        protected static  JToken tkn = null; //与微信通信所需身份证明
        protected static  JToken exp = null; //证明的有效时间
        protected static DateTime wxTokenUpdate = DateTime.Now;

        protected static JToken jtk = null;  //调用微信JS-SDK时所需的身份证明
        protected static JToken jtkExp = null; //证明的有效时间
        protected static DateTime wxJsTkUpdate = DateTime.Now;


        /// <summary>
        /// 此方法用于判断指定的Session是否存在微信用户信息
        /// </summary>
        /// <param name="sn">要检查的Session</param>
        /// <returns>如果包含，应返回能标识唯一微信用户的ID</returns>
        public static string IsWxLogined(HttpContextBase sn)
        {
            string openid= sn.Session["WxUserID"] == null ? "" : sn.Session["WxUserID"].ToString();
            if (string.IsNullOrEmpty(openid))
            {
                var ck = sn.Request.Cookies.Get("WxUserID");
                if (ck != null)
                {
                    openid = ck.Value;
                    sn.Session.Add("WxUserID", openid);
                }
            }
            return openid;
        }

        /// <summary>
        /// 重置指定会话的微信登录状态
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        public static void ResetLoginState(HttpContextBase sn)
        {
            sn.Session.Remove("WxUserID");
            sn.Request.Cookies.Remove("WxUserID");
        }

        public static void CheckMessage()
        {
            var msg = API.NoauthorRequest("MessageSvc@TakeWxMessage").WaitResult();
            if (msg.IsPositive)
            {
                List<DyObject> ms = msg.Data["messages"] as List<DyObject>;
                if (ms == null||ms.Count==0)
                {
                    return;
                }

                string api = @"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + GetWxToken();
                foreach (var m in ms)
                {               
                    //通过设置文件查找消息类型对应的url
                    var tplCfg = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("TplMessages").Find("msgtype", m["msgtype"].ToString());
                    if (tplCfg != null)
                    {
                        string tplid = tplCfg.First("tplid").Value;
                        if (!string.IsNullOrEmpty(tplid))
                        {
                            m.Set("template_id", tplid);
                            string url = tplCfg.First("url").Value;
                            if (!string.IsNullOrEmpty(url))
                            {
                                url = url.Replace("{{objid}}", m["objid"].ToString());
                                m.Set("url",url);
                            }
                            m.Remove("msgtype");
                            m.Remove("objid");
                            WebHelper.PostDataTo(api, m.FastJson());
                        }
                    }                  
                }
            }
            
        }

        #region 与微信服务器的通信方法，不能使用当前平台Session，只能用Cache来交换数据
        /// <summary>
        /// 此方法用于接收微信推送来的消息
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        public void WxMessage(string signature, string timestamp, string nonce, string echostr)
        {
            //TODO:按微信标准验证消息是否来自微信服务器
            if (string.IsNullOrEmpty(echostr))
            {
                try
                {
                    //普通微信消息或事件
                    var cnt = new XmlDocument();
                    cnt.Load(Request.InputStream);
                    var data = XMLSetting.LoadFromStr(cnt.InnerXml);
                    if (!shouldDo(data))
                    {
                        Response.Write("");
                        Response.End();
                        return;
                    }
                    var msgType = data.First("MsgType").Value;

                    //异步发起请求获得微信用户信息
                    //https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
                    WebHelper.BeginGetFrom(new Action<string>(OnLoadWxUInfo), string.Format(@"https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", GetWxToken(), data.First("FromUserName").Value), null);

                    switch (msgType)
                    {
                        case "text":
                            doWxMessageTxt(HttpContext, data);
                            break;
                        case "image":
                            doWxMessageImg(HttpContext, data);
                            break;
                        case "voice":
                            doWxMessageVoice(HttpContext, data);
                            break;
                        case "video":
                            doWxMessageVideo(HttpContext, data);
                            break;
                        case "shortvideo":
                            doWxMessageShortV(HttpContext, data);
                            break;
                        case "location":
                            doWxMessageLocation(HttpContext, data);
                            break;
                        case "link":
                            doWxMessageLnk(HttpContext, data);
                            break;
                        case "event":
                            //对于事件消息，进一步判断事件类型
                            switch (data.First("Event").Value)
                            {
                                case "subscribe":
                                    doWxSubscribe(HttpContext, data);
                                    break;
                                case "unsubscribe":
                                    doWxUnsubscribe(HttpContext, data);
                                    break;
                                case "SCAN":
                                    doWxScanTmpQR(HttpContext, data);
                                    break;
                                case "CLICK":
                                    doWxUserMenuClick(HttpContext, data);
                                    break;
                                default:
                                    Response.Write("success");
                                    Response.End();
                                    break;
                            }
                            break;
                        default:
                            Response.Write("sucess");
                            Response.End();
                            break;
                    }
                    data.Dispose();
                }
                catch(Exception ex)
                {
                    Log("接收到微信消息，处理异常:" + ex.Message);
                    Response.Write("sucess");
                    Response.End();
                }
            }
            else
            {
                Response.Write(echostr);
                Response.End();
                return;
            }
        }

        public ActionResult WxOauthBegin(string fromurl="")
        {
            Log("开始微信网页授权：" + fromurl);
            //微信网页授权：https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 
            string appId = "";
            appId = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appId").Value;

            //1.发起微信OAuth授权申请
            string hst = Request.Url.Host;
            if (Request.Url.Port != 443 & Request.Url.Port != 80)
            {
                hst += ":" + Request.Url.Port;
            }
            string rtnUrl = Url.Encode(Request.Url.Scheme+"://"+hst+"/TLB2B/WxOAuthEnd?fromurl=") + fromurl;
            string getCode = string.Format(@"https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", appId, rtnUrl, "TLB2BOAuth");
            //WebHelper.GetResponseFrom(getCode);
            return Redirect(getCode);
        }

        /// <summary>
        /// 微信OAuth认证第一步通过后，由微信端主动回调
        /// </summary>
        /// <param name="code">用于换取openid</param>
        /// <param name="state">初始用户调用页面</param>
        /// <returns></returns>
        public ActionResult WxOAuthEnd(string code="",string fromurl="")
        {
            string appId = "";
            string appSec = "";
            appId = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appId").Value;
            appSec = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appSec").Value;

            //2.根据返回的code换取access_token和openid
            string getUId = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, appSec,code);
            try {
                string rtn = WebHelper.GetResponseFrom(getUId).ReadToStr();
                JToken oid = null;
                JObject jo = JObject.Parse(rtn);
                if (jo.TryGetValue("openid", out oid))
                {
                    Session.Remove("WxUserID");
                    Session.Add("WxUserID", oid.Value<string>());
                    var sn = API.GetOpenSession(oid.Value<string>(), "wechat");
                    if (sn.IsPositive)
                    {
                        SetLoginStatus(HttpContext, sn.Data);
                        return Redirect(fromurl);
                    }
                    else
                    {
                        return Redirect("/WxPages/WxRegister.html");
                    }
                }
                else
                {
                    Log("用网页授权Code换取access_token失败");
                    return Redirect("/WxPages/WxRegister.html");
                }
            }
            catch(Exception ex)
            {
                Log("微信OAuthEnd with Exception" + ex.Message);
                return Redirect("/Unauthority.html");
            }

        }        

        void OnLoadWxUInfo(string rtn)
        {
            //TODO:使用返回信息中的OpenID作为Key，这样与Session中的WxUserID对应
            JToken oid = null;
            JObject jo = JObject.Parse(rtn);
            if(jo.TryGetValue("openid", out oid))
            {
                HttpContext.Cache.Add(oid.Value<string>()+"-Data", rtn, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }
        }
        #endregion

        #region 为当前平台站点会话提供的服务方法

        public JsonResult GetUserInfo()
        {
            var wu = Session["WxUserID"];
            if (wu == null)
            {
                return Json(FnResult.Failure("TLB2B", "NoWxUserID"));
            }
            else
            {
                object k = HttpContext.Cache.Get(wu.ToString() + "-Data");
                if (k != null)
                {
                    return Json(FnResult.Sucess(k));
                }
                else
                {
                    var uinfo= WebHelper.GetResponseFrom(string.Format(@"https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", GetWxToken(), wu), null);
                    if (uinfo != null)
                    {
                        string rtn = uinfo.ReadToStr();
                        JToken oid = null;
                        JObject jo = JObject.Parse(rtn);
                        if(jo.TryGetValue("openid",out oid))
                        {
                            HttpContext.Cache.Add(oid.Value<string>() + "-Data", rtn, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                            return Json(FnResult.Sucess(rtn));
                        }
                        else
                        {
                            Log("FailureOnGetWxUser");
                            return Json(FnResult.Failure("TLB2B", "FailureOnGetWxUser"));
                        }
                        
                    }
                    else
                    {
                        Log("NoWxUserInfo In Session");
                        return Json(FnResult.Failure("TLB2B", "NoWxUserInfo"));
                    }
                    
                }
            } 
        }

        public JsonResult GetWxTmpQRTicket()
        {
            ResetLoginState(HttpContext);
            //检查当前会话是否已经有临时二维码Ticket

                string tkn = GetWxToken();

                //为当前会话创建一个临时二维码ID，并向微信申请一个二维码Ticket
                var sid=new Random(DateTime.Now.Millisecond).Next(int.MaxValue);
                Session.Add("wxTmpQRSceneId", sid);
                //post https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
                //{"expire_seconds": 6000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
                string jsonRtn=WebHelper.PostDataTo(@"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + tkn, "{\"expire_seconds\": 6000, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\":" +sid+"}}}");
                if (jsonRtn.IndexOf("errcode") < 0)
                {
                    //获取成功，缓存在当前会话中
                    //Session.Add("wxTmpQRTicket", jsonRtn);
                }
                else
                {
                    Log("获取微信临时二维码Ticket失败："+jsonRtn);
                    return GetWxTmpQRTicket();
                }
                return Json(jsonRtn);
        }

        [HttpGet]
        /// <summary>
        /// 检查当前会话对应的微信临时二维码是否被扫
        /// </summary>
        /// <returns></returns>
        public JsonResult IfWxTmpQRScaned()
        {
            var qrId = Session["wxTmpQRSceneId"];   //获取当前会话的临时二维码ID
            if (qrId == null)
            {
                //首先检查当前会话有没有设置临时二维码ID（通过调用GetWxTmpQRTicket函数创建）
                return Json(FnResult.Failure("TLB2B", "NoTmpQRSceneId"));
            }
            else
            {
                var wxUser = HttpContext.Cache.Get(qrId.ToString());
                if (wxUser != null)
                {
                    //如果用户扫了二维码，在Session中保存当前微信用户ID
                    HttpContext.Cache.Remove(qrId.ToString());
                    Session.Remove("WxUserID");
                    Session.Remove("wxTmpQRSceneId");
                    Session.Add("WxUserID", wxUser);
                    return Json(FnResult.Sucess());
                    //Response.Write(FnResult.Sucess().FastJson());
                    //Response.End();
                }
                else
                {
                    return Json(FnResult.Failure("TLB2B", "Unscaned"));
                }
            }
        }

        [HttpGet]
        /// <summary>
        /// 更新微信公众号里的自定义菜单
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateWxMenu()
        {
            var btns = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("buttons");
            if (btns == null)
            {
                return Json(FnResult.Failure("TLB2BController", "NoWxButtonsSetting"));
            }
            //https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
            string rtn = WebHelper.PostDataTo(@"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + GetWxToken(), btns.Value, "utf-8");
            if (rtn.Length > 27)
            {
                return Json(FnResult.Failure("TLB2BController", "WxSettingErr").SetError("wxErr", rtn));
            }
            else
            {
                return Json(FnResult.Sucess(null));
            }
        }

        public JsonResult GetJSSignature(string url="")
        {
            if (IsLogined(HttpContext))
            {
                string jsapi_ticket = GetJSTicket();
                if (jsapi_ticket == "")
                {
                    jsapi_ticket = GetJSTicket(true);
                }
                string noncestr = "Wm3WZYTPz0wzccnW";
                long timestamp = DateTime.Now.Ticks/100000000;


                string str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp.ToString() + "&url=" + url;
                string signature = str.SHA1(false,"utf8");

                string appId = "";
                string appSec = "";

                appId = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appId").Value;
                appSec = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appSec").Value;

                var r = new DyObject().Set("appId", appId)
                                      .Set("timestamp", timestamp)
                                      .Set("nonceStr", noncestr)
                                      .Set("signature", signature)
                                      .Set("url", url);
                return Json(FnResult<DyObject>.Sucess(r));

            }
            else
            {
                return Json(FnResult.Failure("TLB2BController", "Unlogined"));
            }
        }

        [NonAction]
        public string GetJSTicket(bool retry=false)
        {
            //TODO:先检查上次获得的Token是否失效
            if (jtk == null || jtkExp == null || (DateTime.Now - wxJsTkUpdate).TotalSeconds > jtkExp.Value<int>() || retry)
            {
                string tkn = GetWxToken();

                //微信获取JS-SDK-Token的接口: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
                var rtn = WebHelper.GetResponseFrom(@"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+tkn+"&type=jsapi");
                string msg = rtn.ReadToStr();
                if (string.IsNullOrWhiteSpace(msg))
                {
                    return "";
                }
                JObject rsult = JObject.Parse(msg);
                if (rsult.TryGetValue("ticket", out jtk))
                {
                    rsult.TryGetValue("expires_in", out jtkExp);
                    wxJsTkUpdate = DateTime.Now.AddSeconds(-500);
                    return jtk.Value<string>();
                }
                else
                {
                    Log("获取微信JSTicket失败："+msg);
                    return "";
                }
            }
            else
            {
                return jtk.Value<string>();
            }
        }

        public static Stream GetWxMedia(ref string mediaid)
        {
            //http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=
            string tkn = GetWxToken();
            string url = string.Format(@"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", tkn, mediaid);
            var rp = WebHelper.GetResponseFrom(url);
            string cd = rp.GetResponseHeader("Content-disposition");
            if (cd.IndexOf("filename=") > 0)
            {
                string[] pts = cd.Split('=');
                mediaid = pts[1].Remove(0, 1); //移除前后的双引号
                mediaid = mediaid.Remove(mediaid.Length - 1, 1);
            }
            Log("微信返回下载媒体结果:" + cd);
            return rp.GetResponseStream();
        }

        [NonAction]
        static string GetWxToken(bool retry=false)
        {
            //TODO:先检查上次获得的Token是否失效
            if (tkn == null||exp==null|| (DateTime.Now - wxTokenUpdate).TotalSeconds > exp.Value<int>()||retry)
            {
                string appId = "";
                string appSec = "";
             
                appId = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appId").Value;
                appSec = XMLSetting.DefaultSetting.First("WeChatApp").First("tianlianb2b").First("appSec").Value;

                //微信获取Token的接口: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
                var rtn = WebHelper.GetResponseFrom(@"https://api.weixin.qq.com/cgi-bin/token", new DyObject().Set("grant_type", "client_credential").Set("appid", appId).Set("secret", appSec));
                string msg = rtn.ReadToStr();
                if (string.IsNullOrWhiteSpace(msg))
                {
                    return "";
                }
                JObject rsult = JObject.Parse(msg);
                if (rsult.TryGetValue("access_token", out tkn))
                {
                    rsult.TryGetValue("expires_in", out exp);
                    wxTokenUpdate = DateTime.Now;
                    return tkn.Value<string>();
                }
                else
                {
                    Log("GetWxToken"+ rsult.FastJson());
                    return "";
                }           
            }
            else
            {
                //测试token的有效性
                string t = tkn.Value<string>();
                var test = WebHelper.GetResponseFrom("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + t);
                if (test == null||test.ReadToStr().IndexOf("errcode")>0)
                {
                    Log("测试token有效性失败" + test == null ? "" : test.ReadToStr());
                    return GetWxToken(true);
                }
                return tkn.Value<string>();
            }
        }

        #endregion

        #region 处理微信推送来的消息和事件，或主动请求的结果

        bool shouldDo(XMLSetting wxMsg)
        {
            var wxUid = wxMsg.First("FromUserName").Value;
            DyObject sn = HttpContext.Cache.Get(wxUid) as DyObject;
            if (sn == null)
            {
                sn = new DyObject();
                HttpContext.Cache.Add(wxUid,sn, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.High, null);
            }

            if (wxMsg.First("MsgType").Value == "event")
            {
                //对于事件
                if(sn.Has("PrevEvent")&&sn["PrevEvent"].ToString()==(wxMsg.First("FromUserName").Value + wxMsg.First("CreateTime").Value))
                {
                    return false;
                }
                else
                {
                    sn.Set("PrevEvent", wxMsg.First("FromUserName").Value + wxMsg.First("CreateTime").Value);
                    return true;
                }
            }
            else
            {
                //对于普通消息
                if (sn.Has("PrevMessage") && sn["PrevMessage"].ToString() == wxMsg.First("MsgId").Value)
                {
                    return false;
                }
                else
                {
                    sn.Set("PrevMessage", wxMsg.First("MsgId").Value);
                    return true;
                }
            }
        }

        /// <summary>
        /// 处理微信订阅事件
        /// </summary>
        /// <param name="cntx"></param>
        /// <param name="ev"></param>
        static void doWxSubscribe(HttpContextBase cntx, XMLSetting ev)
        {
            var qr = ev.First("EventKey", false);
            if (qr != null)
            {
                //扫描网站上的带参数二维码而订阅公众号,标记所扫的二维码id对应微信用户OpenID
                string ky = qr.Value.Substring(8);
                cntx.Cache.Remove(ky);
                cntx.Cache.Add(ky, ev.First("FromUserName").Value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), CacheItemPriority.AboveNormal, null);
                ResponseTxt(cntx,ev,"欢迎加入天联云企业协同平台！我们致力于为企业打造基于互联网思维的下一代业务管理平台。协同不仅是管理边界的延伸，更是企业管理方式的变革！");
            }
            else
            {
                //其他途径订阅公众号
                ResponseTxt(cntx, ev, "欢迎加入天联云企业协同平台！我们致力于为企业打造基于互联网思维的下一代业务管理平台。协同不仅是管理边界的延伸，更是企业管理方式的变革！");
                //cntx.Response.Write("");
            }
            
        }

        static void doWxScanTmpQR(HttpContextBase cntx, XMLSetting ev)
        {
            var qr = ev.First("EventKey", false);
            if (qr != null)
            {
                //扫描带参数二维码,标记所扫的二维码id对应微信用户OpenID
                string ky = qr.Value;
                cntx.Cache.Add(ky, ev.First("FromUserName").Value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), CacheItemPriority.AboveNormal, null);
                //var sn = API.GetOpenSession(ev.First("FromUserName").Value, "wechat");
                //if (sn.IsPositive)
                //{
                //    CheckTodo(cntx, ev);
                //}
                CheckTodo(cntx, ev);
            }
            else
            {
                ResponseTxt(cntx, ev, "success");
            }           
        }

        static void doWxUnsubscribe(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageTxt(HttpContextBase cntx, XMLSetting msg)
        {
            cntx.Response.Write("");
            cntx.Response.End();
        }

        static void doWxMessageImg(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageVideo(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageShortV(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageLocation(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageLnk(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxMessageVoice(HttpContextBase cntx, XMLSetting msg)
        {

        }

        static void doWxUserMenuClick(HttpContextBase cntx, XMLSetting msg)
        {
            string ek = msg.First("EventKey").Value;

            switch (ek)
            {
                case "todo":
                    CheckTodo(cntx, msg);
                    break;
                case "new":
                    cntx.Response.Write("");
                    cntx.Response.End();
                    break;
                case "myacnt":
                    var wxuser = msg.First("FromUserName").Value;
                    var sn= API.GetOpenSession(wxuser, "wechat");
                    if (sn.IsPositive)
                    {
                        WxNewsItem[] wi = new WxNewsItem[1];
                        wi[0] = new WxNewsItem("您好!" + sn.Data["username"].ToString(), "您的微信号已绑定天联云平台帐号["+sn.Data["mphone"].ToString()+"]", sn.Data["openheadimg"].ToString(), "");
                        ResponseNews(cntx,msg,wi);
                    }
                    else
                    {
                        ResponseTxt(cntx, msg, "抱歉，您的微信号还没有绑定天联云平台帐号");
                    }
                    break;
                case "connactus":
                    string rp = "我们为您提供多种服务方式：";
                    rp += "\n\n";
                    rp += "1.你可以加入天联云官方群直接咨询客服：群号420410228";
                    rp += "\n";
                    rp += "2.你可以在电脑上登录tlunion.com体验更多服务";
                    rp += "\n";
                    rp += "3.如需人工帮助，请拨打";
                    rp += "\n";
                    rp+="0756-7237358/18926929214，我们会有专业的客服耐心为您解答";
                    rp += "\n\n";
                    rp += "谢谢您的关注和使用，期待能为您带来帮助和价值。";
                    ResponseTxt(cntx, msg, rp);
                    break;
                default:
                    break;
            }
        }

        static void CheckTodo(HttpContextBase cntx,XMLSetting msg)
        {
            var itms = new List<WxNewsItem>();
            //查询各种待办，以图文消息方式推送
            UriBuilder ub = new UriBuilder(cntx.Request.Url.Scheme, cntx.Request.Url.Host, cntx.Request.Url.Port);
            string picUrl = "";
            string url = "";

            //查询我的相关待办
            var mytodo = API.NoauthorRequest("MineApp@OpenCountMyTODO")
                            .Set("openuser", msg.First("FromUserName").Value)
                            .Set("opensrc", "wechat")
                            .WaitResult();
            if (!mytodo.IsPositive)
            {
                ResponseTxt(cntx, msg, "请登录天联云协同平台【tlunion.com】并绑定您的微信号，便可在微信中处理相关业务");
            }
            else
            {
                //处理各类todo
                List<DyObject> tds = mytodo.Data["mytodo"] as List<DyObject>;
                foreach (var td in tds)
                {
                    switch (td["todotype"].ToString())
                    {
                        case "ConfirmOrder":
                            //订单确认类待办
                            ub.Path = "/SiteUI/Imgs/wx_newOrder.jpg";
                            picUrl = ub.ToString();
                            ub.Path = "/Sale/WxMyOrders";
                            url = ub.ToString();
                            var count = td["count"].ToString();
                            var wxItm = new WxNewsItem("【" + count + "】份新订单", "您收到了" + count + "份新订单，请尽快确认以免流失销售机会", picUrl, url);
                            itms.Add(wxItm);
                            break;
                        default:
                            break;
                    }
                }
            }
            if (itms.Count > 0)
            {
                ResponseNews(cntx, msg, itms.ToArray());
            }
            else
            {
                ResponseTxt(cntx, msg, "暂时没有需要处理的业务");
            }
        }

        static string msgTpl_txt = @"<xml>
                                    <ToUserName><![CDATA[toUser]]></ToUserName>
                                    <FromUserName><![CDATA[tianlianb2b]]></FromUserName>
                                    <CreateTime>12345678</CreateTime>
                                    <MsgType><![CDATA[text]]></MsgType>
                                    <Content><![CDATA[你好]]></Content>
                                    </xml>";

        static string msgTpl_news = @"<xml>
                                    <ToUserName><![CDATA[toUser]]></ToUserName>
                                    <FromUserName><![CDATA[tianlianb2b]]></FromUserName>
                                    <CreateTime>12345678</CreateTime>
                                    <MsgType><![CDATA[news]]></MsgType>
                                    <ArticleCount>2</ArticleCount>
                                    <Articles>
                                    </Articles>
                                    </xml>";

        static string msgTpl_newsItem = @"<item>
                                        <Title><![CDATA[title1]]></Title> 
                                        <Description><![CDATA[description1]]></Description>
                                        <PicUrl><![CDATA[picurl]]></PicUrl>
                                        <Url><![CDATA[url]]></Url>
                                        </item>";
        /// <summary>
        /// 回覆文本消息给微信服务器
        /// </summary>
        /// <param name="cntx"></param>
        /// <param name="srcMsg"></param>
        /// <param name="msg"></param>
        static void ResponseTxt(HttpContextBase cntx, XMLSetting srcMsg, string msg)
        {
            XMLSetting rsp = XMLSetting.LoadFromStr(msgTpl_txt);
            rsp.First("ToUserName").Value = srcMsg.First("FromUserName").Value;
            rsp.First("CreateTime").Value = ((int)(DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds).ToString();
            rsp.First("Content").Value = msg;
            cntx.Response.Write(rsp.InnerXML);
            cntx.Response.End();
            rsp.Dispose();
        }

        /// <summary>
        /// 回覆图文消息
        /// </summary>
        /// <param name="cntx"></param>
        /// <param name="srcMsg"></param>
        /// <param name="_itms">最大10条，第一条会呈现大图</param>
        static void ResponseNews(HttpContextBase cntx,XMLSetting srcMsg, WxNewsItem[] _itms)
        {
            XMLSetting rsp = XMLSetting.LoadFromStr(msgTpl_news);
            rsp.First("ToUserName").Value = srcMsg.First("FromUserName").Value;
            rsp.First("CreateTime").Value = ((int)(DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds).ToString();
            rsp.First("ArticleCount").Value = _itms.Length.ToString();

            string itms = "";
            XMLSetting rsp_i = XMLSetting.LoadFromStr(msgTpl_newsItem);
            foreach(var i in _itms)
            {
                rsp_i.First("Title").Value = i.Title;
                rsp_i.First("Description").Value = i.Description;
                rsp_i.First("PicUrl").Value = i.PicUrl;
                rsp_i.First("Url").Value = i.Url;
                itms += rsp_i.InnerXML;
            }
            rsp.First("Articles").Value = itms;
            cntx.Response.Write(rsp.InnerXML);
            cntx.Response.End();
            rsp.Dispose();
            rsp_i.Dispose();
            rsp.Dispose();
        }
        #endregion
    }

    /// <summary>
    /// 微信图文消息项
    /// </summary>
    public class WxNewsItem
    {
        public WxNewsItem(string _til,string _dsp,string _picUrl,string _url)
        {
            Title = _til;
            Description = _dsp;
            PicUrl = _picUrl;
            Url = _url;
        }
        public readonly string Title;
        public readonly string Description;
        public readonly string PicUrl;
        public readonly string Url;
    }
}
